/**
 * 番茄时钟计时器核心逻辑
 * 实现基础计时功能和状态管理
 */

class PomodoroTimer {
    constructor() {
        // 默认时间配置（秒）
        this.defaultConfig = {
            workTime: 25 * 60,      // 25分钟工作时间
            shortBreak: 5 * 60,     // 5分钟短休息
            longBreak: 15 * 60,     // 15分钟长休息
            enableShortBreak: true, // 启用短休息
            enableLongBreak: true,  // 启用长休息
            longBreakCycle: 4       // 长休息触发周期
        };
        
        // 当前配置（从本地存储加载或使用默认值）
        this.config = this.loadConfig();
        
        // 状态枚举
        this.states = {
            READY: 'ready',
            WORK: 'work',
            SHORT_BREAK: 'short_break',
            LONG_BREAK: 'long_break',
            PAUSED: 'paused'
        };
        
        // 当前状态
        this.currentState = this.states.READY;
        this.previousState = null;
        
        // 计时器相关
        this.timeLeft = this.config.workTime;
        this.totalTime = this.config.workTime;
        this.timerInterval = null;
        this.isRunning = false;
        
        // 番茄计数
        this.completedPomodoros = 0;
        this.currentCyclePomodoros = 0; // 当前轮次中的番茄数（0-3）
        this.dailyPomodoros = this.loadDailyCount();
        
        // 回调函数
        this.onTick = null;
        this.onStateChange = null;
        this.onComplete = null;
        
        console.log('PomodoroTimer initialized');
    }
    
    /**
     * 开始计时器
     */
    start() {
        if (this.isRunning) {
            console.log('Timer is already running');
            return;
        }

        // 如果是暂停状态，恢复到之前的状态
        if (this.currentState === this.states.PAUSED && this.previousState) {
            this.currentState = this.previousState;
            this.previousState = null;
        } else if (this.currentState === this.states.READY) {
            // 如果是准备状态，开始工作
            this.setState(this.states.WORK);
        }
        // 如果当前时间为0，说明上一个会话已完成，需要重新设置时间
        else if (this.timeLeft <= 0) {
            // 重新设置当前状态的时间
            this.setState(this.currentState);
        }

        this.isRunning = true;
        this.timerInterval = setInterval(() => {
            this.tick();
        }, 1000);

        console.log(`Timer started in ${this.currentState} mode`);
        this.triggerStateChange();
    }
    
    /**
     * 暂停计时器
     */
    pause() {
        if (!this.isRunning) {
            console.log('Timer is not running');
            return;
        }
        
        this.isRunning = false;
        clearInterval(this.timerInterval);
        this.timerInterval = null;
        
        // 保存当前状态并切换到暂停状态
        this.previousState = this.currentState;
        this.currentState = this.states.PAUSED;
        
        console.log('Timer paused');
        this.triggerStateChange();
    }
    
    /**
     * 重置计时器
     */
    reset() {
        this.stop();
        this.currentState = this.states.READY;
        this.previousState = null;
        this.timeLeft = this.config.workTime;
        this.totalTime = this.config.workTime;
        this.currentCyclePomodoros = 0;
        
        console.log('Timer reset');
        this.triggerStateChange();
        this.triggerTick();
    }
    
    /**
     * 停止计时器（内部方法）
     */
    stop() {
        this.isRunning = false;
        if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
        }
    }
    
    /**
     * 计时器滴答
     */
    tick() {
        this.timeLeft--;
        this.triggerTick();
        
        // 时间到达
        if (this.timeLeft <= 0) {
            this.handleTimeUp();
        }
    }
    
    /**
     * 处理时间到达
     */
    handleTimeUp() {
        this.stop();
        
        console.log(`${this.currentState} completed`);
        
        // 根据当前状态决定下一步
        switch (this.currentState) {
            case this.states.WORK:
                this.completeWorkSession();
                break;
            case this.states.SHORT_BREAK:
            case this.states.LONG_BREAK:
                this.completeBreakSession();
                break;
        }
        
        this.triggerComplete();
    }
    
    /**
     * 完成工作时段
     */
    completeWorkSession() {
        this.completedPomodoros++;
        this.currentCyclePomodoros++;
        this.dailyPomodoros++;
        this.saveDailyCount();
        
        console.log(`Work session completed. Total: ${this.completedPomodoros}, Cycle: ${this.currentCyclePomodoros}`);
        
        // 判断下一步状态
        const shouldLongBreak = this.currentCyclePomodoros >= this.config.longBreakCycle;
        
        if (shouldLongBreak && this.config.enableLongBreak) {
            // 达到长休息周期且启用长休息
            this.setState(this.states.LONG_BREAK);
            this.currentCyclePomodoros = 0; // 重置轮次计数
        } else if (this.config.enableShortBreak) {
            // 启用短休息
            this.setState(this.states.SHORT_BREAK);
        } else {
            // 都不启用休息，直接回到工作状态
            if (shouldLongBreak) {
                this.currentCyclePomodoros = 0; // 重置轮次计数
            }
            this.setState(this.states.WORK);
        }
    }
    
    /**
     * 完成休息时段
     */
    completeBreakSession() {
        console.log('Break session completed');
        // 休息结束，回到工作状态
        this.setState(this.states.WORK);
    }
    
    /**
     * 设置状态
     */
    setState(newState) {
        this.currentState = newState;
        
        // 根据状态设置时间
        switch (newState) {
            case this.states.WORK:
                this.timeLeft = this.config.workTime;
                this.totalTime = this.config.workTime;
                break;
            case this.states.SHORT_BREAK:
                this.timeLeft = this.config.shortBreak;
                this.totalTime = this.config.shortBreak;
                break;
            case this.states.LONG_BREAK:
                this.timeLeft = this.config.longBreak;
                this.totalTime = this.config.longBreak;
                break;
        }
        
        console.log(`State changed to: ${newState}`);
        this.triggerStateChange();
        this.triggerTick();
    }
    
    /**
     * 获取格式化的时间显示
     */
    getFormattedTime() {
        const minutes = Math.floor(this.timeLeft / 60);
        const seconds = this.timeLeft % 60;
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
    
    /**
     * 获取进度百分比
     */
    getProgress() {
        return ((this.totalTime - this.timeLeft) / this.totalTime) * 100;
    }
    
    /**
     * 获取状态显示文本
     */
    getStateText() {
        const stateTexts = {
            [this.states.READY]: '准备开始',
            [this.states.WORK]: '专注工作中',
            [this.states.SHORT_BREAK]: '短休息中',
            [this.states.LONG_BREAK]: '长休息中',
            [this.states.PAUSED]: '已暂停'
        };
        return stateTexts[this.currentState] || '未知状态';
    }
    
    /**
     * 加载每日番茄数
     */
    loadDailyCount() {
        try {
            const today = new Date().toDateString();
            const stored = localStorage.getItem('pomodoro_daily_count');
            if (stored) {
                const data = JSON.parse(stored);
                if (data.date === today) {
                    return data.count;
                }
            }
        } catch (error) {
            console.error('Error loading daily count:', error);
        }
        return 0;
    }
    
    /**
     * 保存每日番茄数
     */
    saveDailyCount() {
        try {
            const today = new Date().toDateString();
            const data = {
                date: today,
                count: this.dailyPomodoros
            };
            localStorage.setItem('pomodoro_daily_count', JSON.stringify(data));
        } catch (error) {
            console.error('Error saving daily count:', error);
        }
    }
    
    /**
     * 触发滴答回调
     */
    triggerTick() {
        if (this.onTick) {
            this.onTick({
                timeLeft: this.timeLeft,
                formattedTime: this.getFormattedTime(),
                progress: this.getProgress()
            });
        }
    }
    
    /**
     * 触发状态变化回调
     */
    triggerStateChange() {
        if (this.onStateChange) {
            this.onStateChange({
                state: this.currentState,
                stateText: this.getStateText(),
                isRunning: this.isRunning,
                completedPomodoros: this.completedPomodoros,
                currentCyclePomodoros: this.currentCyclePomodoros,
                dailyPomodoros: this.dailyPomodoros
            });
        }
    }
    
    /**
     * 触发完成回调
     */
    triggerComplete() {
        if (this.onComplete) {
            this.onComplete({
                completedState: this.currentState,
                completedPomodoros: this.completedPomodoros,
                dailyPomodoros: this.dailyPomodoros
            });
        }
    }
    
    /**
     * 设置回调函数
     */
    setCallbacks(callbacks) {
        this.onTick = callbacks.onTick || null;
        this.onStateChange = callbacks.onStateChange || null;
        this.onComplete = callbacks.onComplete || null;
    }
    
    /**
     * 获取当前状态信息
     */
    getStatus() {
        return {
            state: this.currentState,
            stateText: this.getStateText(),
            isRunning: this.isRunning,
            timeLeft: this.timeLeft,
            formattedTime: this.getFormattedTime(),
            progress: this.getProgress(),
            completedPomodoros: this.completedPomodoros,
            currentCyclePomodoros: this.currentCyclePomodoros,
            dailyPomodoros: this.dailyPomodoros
        };
    }
    
    /**
     * 加载配置
     */
    loadConfig() {
        try {
            const stored = localStorage.getItem('pomodoro_config');
            if (stored) {
                const config = JSON.parse(stored);
                // 合并默认配置和存储的配置
                return { ...this.defaultConfig, ...config };
            }
        } catch (error) {
            console.error('Error loading config:', error);
        }
        return { ...this.defaultConfig };
    }
    
    /**
     * 保存配置
     */
    saveConfig() {
        try {
            localStorage.setItem('pomodoro_config', JSON.stringify(this.config));
            console.log('Config saved:', this.config);
        } catch (error) {
            console.error('Error saving config:', error);
        }
    }
    
    /**
     * 更新配置
     */
    updateConfig(newConfig) {
        // 停止当前计时器
        const wasRunning = this.isRunning;
        this.stop();
        
        // 更新配置
        this.config = { ...this.config, ...newConfig };
        this.saveConfig();
        
        // 重置到准备状态
        this.currentState = this.states.READY;
        this.previousState = null;
        this.timeLeft = this.config.workTime;
        this.totalTime = this.config.workTime;
        
        console.log('Config updated:', this.config);
        
        // 触发状态更新
        this.triggerStateChange();
        this.triggerTick();
    }
    
    /**
     * 获取配置
     */
    getConfig() {
        return { ...this.config };
    }
    
    /**
     * 重置配置为默认值
     */
    resetConfig() {
        this.updateConfig(this.defaultConfig);
    }
}